"use client";

import { useState } from "react";
import { useAuth } from "../lib/auth";

export interface AuthGateProps {
  children: React.ReactNode;
}

export function AuthGate({ children }: AuthGateProps) {
  const { authenticated, login } = useAuth();
  const [input, setInput] = useState("");

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!input.trim()) return;
    await login(input.trim()).catch(() => alert("Authentication failed"));
  }

  if (!authenticated) {
    return (
      <div className="grid min-h-screen place-items-center bg-slate-950 text-slate-100">
        <form onSubmit={handleSubmit} className="surface-panel w-full max-w-sm space-y-4 p-6">
          <header>
            <h1 className="text-xl font-semibold">Agent-Society Control Center</h1>
            <p className="text-sm text-slate-400">Enter your access token to continue.</p>
          </header>
          <input
            value={input}
            onChange={event => setInput(event.target.value)}
            type="password"
            className="w-full rounded-lg border border-slate-700/50 bg-slate-900/70 px-3 py-2 text-sm focus:border-sky-500 focus:outline-none"
            placeholder="Access token"
          />
          <button
            type="submit"
            className="w-full rounded-lg bg-sky-600 px-3 py-2 text-sm font-semibold text-white transition hover:bg-sky-500"
          >
            Enter Control Center
          </button>
        </form>
      </div>
    );
  }

  return <>{children}</>;
}
